package top.wshape1.rpc.consumer;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-02
 */

public class ConsumerSession {

    /**
     * 存储与provider的所有连接的channel
     */
    private final Map<String, Channel> channelMap = new ConcurrentHashMap<>();

    public Channel getChannel(String inetHost, int inetPort) {
        String key = inetHost + ":" + inetPort;
        return channelMap.get(key);
    }

    public void setChannel(String inetHost, int inetPort, Channel channel) {
        String key = inetHost + ":" + inetPort;
        channelMap.put(key, channel);
    }

    public Channel removeChannel(String inetHost, int inetPort) {
        String key = inetHost + ":" + inetPort;
        return channelMap.remove(key);
    }

    public void clearAndClose() {
        for (Map.Entry<String, Channel> entry : channelMap.entrySet()) {
            entry.getValue().close();
        }
        // 虽然每个Channel创建的时候都在closeFuture里removeChannel
        // 但是还是再执行一次clear
        channelMap.clear();
    }

}
